/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.psc.controllers;

import com.mycompany.psc.data.Roles;
import com.mycompany.psc.ejb.UsersManager;
import com.mycompany.psc.entities.Department;
import java.util.List;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.inject.Inject;
import javax.inject.Named;
import org.primefaces.context.RequestContext;

/**
 *
 * @author A7med
 */
@Named
@RequestScoped
public class RegisterBean {

    @EJB
    private UsersManager persistData;
    private String userName;
    private String password;

    private Department role;
    @Inject
    DepartmentsController dc;

    public Department getRole() {
        return role;
    }

    public void setRole(Department role) {
        this.role = role;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void register(javax.faces.event.ActionEvent evt) {
        RequestContext context = RequestContext.getCurrentInstance();
        FacesContext fc = FacesContext.getCurrentInstance();
        boolean successful = false;
        System.out.println("registering");
        if (!persistData.IsUserExists(userName)) {
            if (persistData.SaveUser(userName, password, role) == 0) {
                fc.addMessage("", new FacesMessage(FacesMessage.SEVERITY_INFO, "Registeration Succeeded", "User with the name " + userName + " created successfully"));
                successful = true;
            } else {
                fc.addMessage("", new FacesMessage(FacesMessage.SEVERITY_INFO, "Registeration Failed", "Database errror. Please try again later"));
            }
        } else {
            fc.addMessage("", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Registeration Failed", "User with the name " + userName + " already exists"));
        }
        context.addCallbackParam("successful", successful);
    }

    public SelectItem[] getRoles() {
        List<Department> list = dc.getAllUsersDeparts();
        SelectItem[] items = new SelectItem[list.size()];
        int i = 0;
        for (Department g : list) {
            items[i++] = new SelectItem(g, g.getName());
        }
        return items;
    }

}
